package com.bdqn.controller;

import com.alibaba.fastjson.JSON;
import com.bdqn.pojo.StudentInfo;
import com.bdqn.service.StudentInfoService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学生信息控制器
 *
 * @Entity com.bdqn.pojo.StudentInfo
 */
@Controller
@RequestMapping("/student")
public class StudentInfoController {

    @Resource
    private StudentInfoService studentInfoService;

    /**
     * 获得所有学生信息数据
     *
     * @return
     */
    @GetMapping("/list")
    public String getList(HttpServletRequest request) {
        // 获取学生信息表的数据
        List<StudentInfo> list = studentInfoService.getList();

        // 把数据设置到作用域
        request.setAttribute("list", list);
        return "list";
    }

    /**
     * 获得所有学生信息数据
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/del")
    public String delete(@RequestParam("sid") Long sid) {
        int delete = studentInfoService.delete(sid);
        Map<String, Boolean> result = new HashMap<>();
        result.put("isok", delete == 1);
        return JSON.toJSONString(result);
    }

    /**
     * 去到新增页面
     *
     * @return
     */
    @GetMapping("/add")
    public String toAdd() {
        return "add";
    }

    /**
     * 添加学生信息
     *
     * @param studentInfo
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/add", produces = "text/html;charset=UTF-8")
    public String doAdd(HttpServletRequest request, StudentInfo studentInfo) {
        int add = studentInfoService.add(studentInfo);
        if (add == 1) {
            return "<script>alert(\"添加成功！\");location.href=\"" + request.getContextPath() + "/student/list\";</script>";
        } else {
            return "<script>alert(\"添加失败！\");</script>";
        }
    }

    /**
     * 根据ID查询学员信息去到修改页面
     *
     * @param sid
     * @return
     */
    @GetMapping("/update/{sid}")
    public String toUpdate(HttpServletRequest request, @PathVariable("sid") Long sid) {
        // 获取学生信息表的单个数据
        StudentInfo studentInfo = studentInfoService.getById(sid);
        // 设置到作用域
        request.setAttribute("student", studentInfo);
        return "update";
    }

    /**
     * 根据ID修改学生信息
     *
     * @param studentInfo
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/update", produces = "text/html;charset=UTF-8")
    public String doUpdate(HttpServletRequest request, StudentInfo studentInfo) {
        int update = studentInfoService.update(studentInfo);
        if (update == 1) {
            return "<script>alert(\"修改成功！\");location.href=\"" + request.getContextPath() + "/student/list\";</script>";
        } else {
            return "<script>alert(\"修改失败！\");</script>";
        }
    }

}




